/**
 * 验证工具函数
 */

import { REGEX } from '../constants/common';

/**
 * 验证邮箱
 */
export const validateEmail = (email: string): boolean => {
  return REGEX.EMAIL.test(email);
};

/**
 * 验证手机号
 */
export const validatePhone = (phone: string): boolean => {
  return REGEX.PHONE.test(phone);
};

/**
 * 验证密码强度
 */
export const validatePassword = (password: string): boolean => {
  return REGEX.PASSWORD.test(password);
};

/**
 * 验证用户名
 */
export const validateUsername = (username: string): boolean => {
  return REGEX.USERNAME.test(username);
};

/**
 * 验证代码格式
 */
export const validateCode = (code: string): boolean => {
  return REGEX.CODE.test(code);
};

/**
 * 验证身份证号
 */
export const validateIdCard = (idCard: string): boolean => {
  if (!idCard) return false;
  
  // 18位身份证号码验证
  if (idCard.length === 18) {
    const regex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
    if (!regex.test(idCard)) return false;
    
    // 校验码验证
    const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
    
    let sum = 0;
    for (let i = 0; i < 17; i++) {
      sum += parseInt(idCard[i]) * weights[i];
    }
    
    const checkCode = checkCodes[sum % 11];
    return idCard[17].toUpperCase() === checkCode;
  }
  
  return false;
};

/**
 * 验证URL
 */
export const validateUrl = (url: string): boolean => {
  try {
    new URL(url);
    return true;
  } catch {
    return false;
  }
};

/**
 * 验证IP地址
 */
export const validateIP = (ip: string): boolean => {
  const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
  if (!ipv4Regex.test(ip)) return false;
  
  const parts = ip.split('.');
  return parts.every(part => {
    const num = parseInt(part);
    return num >= 0 && num <= 255;
  });
};

/**
 * 验证端口号
 */
export const validatePort = (port: string | number): boolean => {
  const portNum = typeof port === 'string' ? parseInt(port) : port;
  return !isNaN(portNum) && portNum >= 1 && portNum <= 65535;
};

/**
 * 验证JSON格式
 */
export const validateJSON = (str: string): boolean => {
  try {
    JSON.parse(str);
    return true;
  } catch {
    return false;
  }
};

/**
 * 验证文件类型
 */
export const validateFileType = (file: File, allowedTypes: string[]): boolean => {
  return allowedTypes.includes(file.type);
};

/**
 * 验证文件大小
 */
export const validateFileSize = (file: File, maxSize: number): boolean => {
  return file.size <= maxSize;
};

/**
 * 验证年龄
 */
export const validateAge = (birthDate: string | Date, minAge = 0, maxAge = 150): boolean => {
  const birth = new Date(birthDate);
  const now = new Date();
  const age = now.getFullYear() - birth.getFullYear();
  
  return age >= minAge && age <= maxAge;
};

/**
 * 验证银行卡号
 */
export const validateBankCard = (cardNumber: string): boolean => {
  // 移除空格和连字符
  const cleaned = cardNumber.replace(/[\s-]/g, '');
  
  // 检查是否只包含数字
  if (!/^\d+$/.test(cleaned)) return false;
  
  // 检查长度（一般为16-19位）
  if (cleaned.length < 16 || cleaned.length > 19) return false;
  
  // Luhn算法验证
  let sum = 0;
  let isEven = false;
  
  for (let i = cleaned.length - 1; i >= 0; i--) {
    let digit = parseInt(cleaned[i]);
    
    if (isEven) {
      digit *= 2;
      if (digit > 9) {
        digit -= 9;
      }
    }
    
    sum += digit;
    isEven = !isEven;
  }
  
  return sum % 10 === 0;
};

/**
 * 表单验证规则生成器
 */
export const createValidationRules = {
  required: (message: string) => ({
    required: true,
    message,
  }),
  
  email: (message = '请输入有效的邮箱地址') => ({
    validator: (_: any, value: string) => {
      if (!value || validateEmail(value)) {
        return Promise.resolve();
      }
      return Promise.reject(new Error(message));
    },
  }),
  
  phone: (message = '请输入有效的手机号') => ({
    validator: (_: any, value: string) => {
      if (!value || validatePhone(value)) {
        return Promise.resolve();
      }
      return Promise.reject(new Error(message));
    },
  }),
  
  password: (message = '密码至少6位，包含字母和数字') => ({
    validator: (_: any, value: string) => {
      if (!value || validatePassword(value)) {
        return Promise.resolve();
      }
      return Promise.reject(new Error(message));
    },
  }),
  
  minLength: (min: number, message?: string) => ({
    min,
    message: message || `至少输入${min}个字符`,
  }),
  
  maxLength: (max: number, message?: string) => ({
    max,
    message: message || `最多输入${max}个字符`,
  }),
}; 